package com.leonardo.beanme.metadatahandlers.tags;

import org.xml.sax.Attributes;

import com.leonardo.beanme.exceptions.XmlReadingException;
import com.leonardo.beanme.metadatahandlers.FormMetadataContainer;
import com.leonardo.beanme.metadatahandlers.TagHandler;

public class BeanTagHandler extends TagHandler {

	private boolean insideBeanTag = false;
	
	public String getTagName() {
		return "bean";
	}
	
	public void endTag() {
		super.endTag();
		owner.addBean();
		insideBeanTag = false;
	}

	public void startTag(Attributes attributes) {
		if(insideBeanTag)
			throw new XmlReadingException("Incorrect place of tag bean inside " +
					"declaration of " + owner.getBeanInfo().getId());
		owner.setBeanInfo(newBean(attributes));
		insideBeanTag = true;
	}
	
	private FormMetadataContainer newBean(Attributes attributes) {
		int idIndex = attributes.getIndex("id"); 
		int typeIndex = attributes.getIndex("type");
		
		if(idIndex < 0)
			throw new XmlReadingException("Bean without id found");
		else if(typeIndex < 0) 
			throw new XmlReadingException("Missing type attribute in " + attributes.getValue(idIndex));
		
		String beanId = attributes.getValue(idIndex) ;
		String typeStr = attributes.getValue(typeIndex);
		int type;
		if("additional".equals(typeStr))
			type = FormMetadataContainer.ADDITIONAL;
		else if("exclusive".equals(typeStr))
			type = FormMetadataContainer.EXCLUSIVE;
		else
			throw new XmlReadingException("Incorrect type " + typeStr + " on bean " + beanId);
		
		return new FormMetadataContainer(beanId, type);
	}
}
